/**
 * 
 */
package reservationController;

import java.awt.Dialog;
import java.net.URL;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import mail.MailSender;

import org.apache.commons.lang3.StringUtils;

import encryption.Encrypt;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import rentReturnController.RentController;
import reservationEntity.ReservationEntity;
import reservationLogic.ReservationLogic;
import userController.Navigator;
import userEntity.UserEntity;
import userLogic.MembershipLogic;
import validator.Validator;

/**
 * @author Aakash Singh
 *
 */
public class ReservationController implements Initializable{

	@FXML
	private  DatePicker reservation_pickup_date;
	@FXML
	private  DatePicker return_date;

	@FXML
	private ComboBox<String> reservation_vehicle_class;
	@FXML
	private ComboBox<String> reservation_driver_age;
	@FXML
	private ComboBox<String> reservation_vehicle_capacity;
	@FXML
	private ComboBox<String> reservation_vehicle_equipments;
	@FXML
	private ComboBox<String> reservation_pickup_time;
	@FXML
	private ComboBox<String> reservation_return_time;
	@FXML
	private ComboBox<String> reservation_vehicle_type;
	@FXML
	private Button reservation_price_quote;

	@FXML
	private TextField creditCardNo;
	@FXML
	private TextField expirydate;
	@FXML
	private TextField reservationID;
	@FXML
	private TextField reservationPhoneNumber;
	@FXML
	private TextField reservationDate;
	@FXML
	private TextField vehicleClass;
	@FXML
	private TextField vehicleType;
	@FXML
	private TextField returnDate;
	@FXML
	private TextField pickupDate;
	@FXML
	private TextField additionalEquip;
	@FXML
	private TextField vehicleSpec;
	@FXML
	private TextField rentalCost;
	@FXML
	private TextField insuranceCost;
	@FXML
	private TextField estimatePrice;
	@FXML
	private Label genReservationID;

	@FXML
	private TextField custEmailID;
	@FXML
	private TextField custName;
	@FXML
	private TextField customerPhoneNumber;
	@FXML
	private TextArea custAddress;
	@FXML
	private Button contReservation;
	@FXML
	private Label emailLabel;
	@FXML
	private Label addressLabel;
	@FXML
	private Label errorText1;
	@FXML
	private Label isMember;
	@FXML
	private Button checkMember;
	@FXML
	private Button cancelConfirm;
	
	@FXML
	private Label cancelResLabel;

	public static boolean alreadyMember=false;
	public static int page=-1;
	private  String custPhoneNumber;
	private static ReservationEntity reservation = new ReservationEntity();
	private static ReservationEntity cancelReservation = new ReservationEntity();


	/**
	 * @param phoneNumber the phoneNumber to set
	 */
	public void setPhoneNumber(String phoneNumber) {
		this.custPhoneNumber = phoneNumber;
	}
	/**
	 * This method is the event handler method for a button on the Customer Information Page
	 * It checks whether the user is already registered based on the phone number entered,
	 * If he is then his information is displayed
	 * If not then the user is asked to enter further details.
	 * @pre The name and the phone number fields are not empty and are valid
	 * @post Entered details are checked in database if he is an registered user
	 * @param event
	 */
	@FXML
	public void checkMember(ActionEvent event)
	{
		isMember.setVisible(false);
		errorText.setVisible(false);
		if(!custName.getText().isEmpty())
			if(!customerPhoneNumber.getText().isEmpty())
			{
				if(!Validator.validatePhoneNumber(customerPhoneNumber.getText().trim()))
				{
					errorText.setText("Enter a valid Phone Number");
					errorText.setVisible(true);
					return;
				}
				if(!Validator.validateName(custName.getText().trim()))
				{
					errorText.setText("Enter a valid Name of Customer");
					errorText.setVisible(true);
					return;
				}

				ReservationLogic rl = new ReservationLogic();
				UserEntity us = new UserEntity();
				try {
					us=rl.checkMember(customerPhoneNumber.getText());
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					errorText.setText("DB ERROR");
					errorText.setVisible(true);
				}
				if(us!=null)
				{
					isMember.setText("Please confirm Customer Details...");
					isMember.setVisible(true);
					custEmailID.setText(us.getEmailID());
					custAddress.setText(us.getAddress());
					custAddress.setEditable(false);
					custEmailID.setEditable(false);
					contReservation.setVisible(true);
					alreadyMember=true;
				}
				else
				{
					isMember.setText("Please enter Other details as Well...");
					isMember.setVisible(true);

				}
				checkMember.setVisible(false);
				custEmailID.setVisible(true);
				custAddress.setVisible(true);
				emailLabel.setVisible(true);
				addressLabel.setVisible(true);
				contReservation.setVisible(true);	
			}
			else
			{
				errorText.setText("Please enter a valid Phone Number");
				errorText.setVisible(true);
			}
		else
		{
			errorText.setText("Please enter a Name");
			errorText.setVisible(true);
		}
	}

	public void makeReservation()
	{
		Navigator.loadStackPane(Navigator.ClerkReservationInitialFXML);


	}
	/**
	 * This method is an event handler of the button on the Customer Information page 
	 * It validates the user inputs and if all are valid then it makes an entry
	 * in the database table to store customer information. 
	 * Thereafter it navigates to the Reservation Initial Page.
	 * @param event
	 */
	@FXML
	public void doReservation(ActionEvent event){
		page=0;
		errorText1.setVisible(false);
		if(!custName.getText().isEmpty() && !customerPhoneNumber.getText().isEmpty() && !custEmailID.getText().isEmpty())
		{

			if(!Validator.validateEmailID(custEmailID.getText()))
			{
				errorText1.setText("Email ID is not valid");
				errorText1.setVisible(true);
				return;
			}
			if(!alreadyMember)
			{	ReservationLogic rl=new ReservationLogic();
				UserEntity us = new UserEntity(custName.getText(),customerPhoneNumber.getText(),custEmailID.getText(),custAddress.getText());
				try {
					if(!rl.registerUser(us))
					{
						errorText1.setText("The Customer cannot be registered.. Please try again !!");
						errorText.setVisible(true);
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					errorText.setText("DB ERROR");
					errorText.setVisible(true);
				}
			}
			reservation.setPhoneNumber(customerPhoneNumber.getText());
			Navigator.loadStackPane(Navigator.ReservationInitialFXML);
		}
		else
		{
			errorText1.setText("Please Enter all the required fields");
			errorText1.setVisible(true);
		}
	}

	/**
	 * This method fetches the additonal Equipment from the service Class method for the particular Vehicle Class selected
	 */
	public void fetchAdditionalEquipment(){
		reservation_vehicle_equipments.getItems().clear();
			ReservationLogic rl = new ReservationLogic();
			List<String> capacityList= new ArrayList<String>();
			try {
				capacityList = rl.fetchAddEquip(reservation_vehicle_class.getValue().toString());
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				errorText.setText("DB ERROR");
				errorText.setVisible(true);
			}
			reservation_vehicle_equipments.getItems().add("None");
			reservation_vehicle_equipments.getItems().addAll(capacityList);
			reservation_vehicle_equipments.getItems().add("Both");
			reservation_vehicle_equipments.setVisible(true);
	}
	/**
	 * This method fetches the specification of the vehicle according to the Vehicle Class the user had selected
	 * @param event
	 */
	@FXML
	public void fetchSpecification(ActionEvent event){
		errorText1.setVisible(false);
		errorText.setVisible(false);
		reservation_vehicle_capacity.getItems().clear();
		reservation_vehicle_equipments.getItems().clear();
		if(reservation_vehicle_class.getValue()!=null && reservation_driver_age.getValue()!=null)
		{
			if(reservation_driver_age.getValue().equalsIgnoreCase("Less than 21"))
			{
				errorText1.setText("Reservation NOT allowed for this Age Drivers");
				errorText1.setVisible(true);
				return;
			}
			ReservationLogic rl = new ReservationLogic();

			List<String> capacityList= new ArrayList<String>();
			try {
				capacityList = rl.fetchSpecification(reservation_vehicle_class.getValue().toString());
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				errorText.setText("DB ERROR");
				errorText.setVisible(true);
			}
			reservation_vehicle_capacity.getItems().addAll(capacityList);
			reservation_vehicle_capacity.setVisible(true);
			fetchAdditionalEquipment();

		}


	}

	/**
	 * This method fetches the available Vehicle Type according to the previous selections made by the user
	 * @param event
	 * @return
	 */
	@FXML
	public void fetchVehicleType( ActionEvent event){
		errorText.setVisible(false);
		reservation_vehicle_type.getItems().clear();
		if(reservation_vehicle_class.getValue()!=null && reservation_driver_age.getValue()!=null && reservation_vehicle_capacity.getValue()!=null && reservation_vehicle_equipments.getValue()!=null)
		{
		ReservationLogic rl = new ReservationLogic();
		List<String> list = new ArrayList<String>();
		
		try {
			list = rl.fetchVehicleType(reservation_vehicle_capacity.getValue().toString(),reservation_vehicle_class.getValue().toString(),reservation_pickup_date.getValue(),return_date.getValue());
			
			reservation_vehicle_type.getItems().addAll(list);
			reservation_vehicle_type.setVisible(true);
			if(list.size()==0)
			{
				errorText.setText("No Vehicles Type Available");
				errorText.setVisible(true);
				reservation_vehicle_type.getItems().clear();
				reservation_price_quote.setDisable(true);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			errorText.setText("DB ERROR");
			errorText.setVisible(true);
		}
		}

	}
	@FXML
	private Label errorText;

	/**
	 * This method performs checks on the reservation pick up date, reservation pick up time, return date , return time 
	 * when all of them are selected. Any error situations are reported on the screen.
	 * @param event
	 */
	@FXML
	public void checkDateTime(ActionEvent event)
	{
		clearingChoices();
		setAllChoicesInvisible();
		errorText.setVisible(false);

		//Checking for valid dates
		if(reservation_pickup_date.getValue()!=null && return_date.getValue()!=null && reservation_pickup_time.getValue()!=null && reservation_return_time.getValue()!=null)
		{
			ReservationLogic rl = new ReservationLogic();

			if(rl.isDateBeforeCurrentDate(reservation_pickup_date.getValue()))
			{	errorText.setText("Please enter a present OR future date");
			errorText.setVisible(true);
			return;
			}

			if(rl.isDateBeforeCurrentDate(return_date.getValue()))
			{	errorText.setText("Please enter a present OR future date");
			errorText.setVisible(true);
			return;
			}

			if(rl.isPickupDateBeforeeturnDate(reservation_pickup_date.getValue(), return_date.getValue()))
			{
				errorText.setText("Pick Up Date should be on or before the Return date");
				errorText.setVisible(true);
				return;
			}
			selectClassAndAge();
		}

	}
	
	/**
	 * This method populates the combo-box for the Driver's Age and the Vehicle Class
	 */
	public void selectClassAndAge()
	{
		reservation_driver_age.getItems().addAll("Less than 21","Between 21 and 24","More than 24");
		reservation_vehicle_class.getItems().addAll("Car","Truck");
		reservation_driver_age.setVisible(true);
		reservation_vehicle_class.setVisible(true);
	}

	/**
	 * Method to make all the choice making list invisible to the user which would
	 * aid to the incremental selection of the reservation to be done
	 */
	public void setAllChoicesInvisible()
	{
		errorText.setVisible(false);
		reservation_driver_age.setVisible(false);
		reservation_vehicle_class.setVisible(false);
		reservation_vehicle_equipments.setVisible(false);
		reservation_vehicle_type.setVisible(false);
		reservation_vehicle_capacity.setVisible(false);
	}

	/**
	 * Method to clear all the choices selected on the Initial Reservation Page
	 */
	public void clearingChoices()
	{
		reservation_driver_age.getItems().clear();
		reservation_vehicle_class.getItems().clear();
		reservation_vehicle_equipments.getItems().clear();
		reservation_vehicle_capacity.getItems().clear();
		reservation_vehicle_type.getItems().clear();
	}

	/**
	 * Event handler of a button on the Estimated Price Quote page to allow the user
	 * to go back to the initial Reservation Page so as to modify the same
	 * @param event
	 */
	@FXML
	public void modifyReservation(ActionEvent event){
		page=2;
		Navigator.loadStackPane(Navigator.ReservationInitialFXML);

	}
	/**
	 * Event handler of the Initial Reservation Page which will then store the enteries in a Reservation
	 * Entity and navigate to the PriceQuote page
	 * @pre User Inputs are taken for the reservation
	 * @post the price estimated related to the reservation  is displayed
	 * @param event
	 */
	@FXML
	public void viewPriceQuote(ActionEvent event){
		errorText1.setVisible(false);
		if(reservation_vehicle_type.getValue()==null)
		{
			errorText1.setText("Please select the Vehicle Type");
			errorText1.setVisible(true);
			return;

		}
		reservation.setPickUpDate(reservation_pickup_date.getValue());
		reservation.setPickUpTime(reservation_pickup_time.getValue().toString());
		reservation.setDriverAge(reservation_driver_age.getValue().toString());
		reservation.setReturnDate(return_date.getValue());
		reservation.setReturnTime(reservation_return_time.getValue().toString());
		reservation.setVehicleClass(reservation_vehicle_class.getValue().toString());
		reservation.setVehicleType(reservation_vehicle_type.getValue().toString());
		reservation.setVehicleSpec(reservation_vehicle_capacity.getValue().toString());

		ArrayList<String> additionalEquip = new ArrayList<String>();
		ReservationLogic rl= new ReservationLogic();
		if(reservation_vehicle_equipments.getValue().toString().equalsIgnoreCase("None"))
			additionalEquip=null;
		else if (reservation_vehicle_equipments.getValue().toString().equalsIgnoreCase("Both"))
		{
			try {
				additionalEquip=rl.fetchAddEquip(reservation_vehicle_class.getValue().toString());
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				errorText.setText("DB ERROR");
				errorText.setVisible(true);
			}
		}
		else
		{
			additionalEquip.add(reservation_vehicle_equipments.getValue());	
		}
		reservation.setAdditionalEquip(additionalEquip);

		calculatePriceEstimate();
		page=1;
		Navigator.loadStackPane(Navigator.ReservationPriceQuoteFXML);


	}
	@FXML
	ListView<String> priceEst;


	/**
	 * Method to calculate the price estimate for a given reservation
	 * @pre The reservation inputs are fetched from user
	 * @post estimated price cost based on the inputs from the user are displayed
	 */
	public void calculatePriceEstimate()
	{

		String [] pickupTime = reservation.getPickUpTime().split(":");
		String pTime=pickupTime[0];
		String [] returnTime = reservation.getReturnTime().split(":");
		String rTime= returnTime[0];
		LocalDate pDate=reservation.getPickUpDate();
		LocalDate rDate = reservation.getReturnDate();
		int weeks=0,days=0,hours=0;
		int pHour=Integer.parseInt(pTime);
		int rHour=Integer.parseInt(rTime);
		weeks=(rDate.getDayOfYear()-pDate.getDayOfYear())/7;
		days=(rDate.getDayOfYear()-pDate.getDayOfYear())%7;
		if(pHour>rHour)
		{
			if(days==0)
			{
				weeks=weeks-1;
				days=6;
			}
			else
				days=days-1;

			hours =(24-pHour)+rHour;
			System.out.println("Weeks :"+weeks+"  Days: "+days+" Hours: "+hours);
		}
		else if(pHour<=rHour)
		{ 
			hours = rHour-pHour;
			System.out.println("Weeks :"+weeks+"  Days: "+days+" Hours: "+hours);
		}

		ReservationLogic rl = new ReservationLogic();
		ReservationEntity reserve=new ReservationEntity();
		try {
			reserve = rl.calculatePriceQuote(weeks, days, hours, reservation.getVehicleType(), reservation.getDriverAge(), reservation.getAdditionalEquip());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			errorText.setText("DB ERROR");
			errorText.setVisible(true);
		}
		reservation.setRentalCost(reserve.getRentalCost());
		reservation.setInsuranceCost(reserve.getInsuranceCost());
		reservation.setEstimatedCost(Validator.formatDoubleWithRound(reserve.getEstimatedCost()));
		reservation.setTax(reserve.getTax());
		reservation.setAgeFine(reserve.getAgeFine());
		reservation.setAdditionalEquipmentFees(reserve.getAdditionalEquipmentFees());
		reservation.setFees(reserve.getFees());
		System.err.println("Inside the cal Rental :"+reserve.getRentalCost()+"   "+reservation.getRentalCost());
	}


	@FXML
	public void showReservation(ActionEvent event){
		// restore the values and show reservation page
	}

	/**
	 * Event handler method of the priceQuote Page so as the navigate to the credit card page
	 * @pre The customer proceeds from the price quote page 
	 * @post The Credit card page is loaded
	 * @param event
	 */
	@FXML
	public void getCreditCardDetails(ActionEvent event){
		page=3;
		Navigator.loadStackPane(Navigator.CreditCardInfoFXML);

	}

	/**
	 * Event handler Method for a finalize reservation page button to store the reservation details in the database
	 * @param event
	 */
	@FXML
	public void storeReservation(ActionEvent event){
		errorText.setVisible(false);
		if(!expirydate.getText().isEmpty() && !creditCardNo.getText().isEmpty())
		{

			if(!Validator.validateStringContainsInteger(creditCardNo.getText()) || creditCardNo.getText().length()!=16)
			{
				errorText.setText("Please Enter a valid Credit Card Number");
				errorText.setVisible(true);
				return;
			}
			if(!Validator.validateStringContainsInteger(expirydate.getText()) || expirydate.getText().length()!=4)
			{
				errorText.setText("Please Enter a valid Expiry Date");
				System.out.println(expirydate.getText().substring(0,1));
				errorText.setVisible(true);
				return;
			}

			System.out.println("Expiry Year :"+expirydate.getText().substring(2, 4)+" Expiry Month :"+expirydate.getText().substring(0,2));

			if(Integer.parseInt(expirydate.getText().substring(2, 4)) < (LocalDate.now().getYear()%100))
			{
				errorText.setText("CC Expiry Year is a past year");
				System.out.println(expirydate.getText().substring(2, 4));
				errorText.setVisible(true);
				return;
			}
			else
				if((Integer.parseInt(expirydate.getText().substring(2, 4)) == (LocalDate.now().getYear()%100)) && Integer.parseInt(expirydate.getText().substring(0,2)) < (LocalDate.now().getMonthValue()))
				{

					errorText.setText("CC Expiry Year is a past month");
					errorText.setVisible(true);
					return;
				}
				else if(Integer.parseInt(expirydate.getText().substring(0,2))>12 || Integer.parseInt(expirydate.getText().substring(0,2))<1)
				{
					errorText.setText("CC Expiry has invalid month");
					errorText.setVisible(true);
					return;
				}

			ReservationLogic rl = new ReservationLogic();

			reservation.setCreditCardNumber(creditCardNo.getText());
			reservation.setExpiryDate(Integer.parseInt(expirydate.getText()));
		}
		else
		{
			errorText.setText("Please enter both the Credit Card number and Expiry Date");
			errorText.setVisible(true);
			return;
		}

		page=4;
		try
		{
			ReservationLogic rl = new ReservationLogic();
			reservation.setReservationID( rl.storeReservation(reservation));
			
				MembershipLogic logic = new MembershipLogic();
				String mailId = logic.fetchEmailID(reservation.getPhoneNumber());
			
			if(mailId != null && !StringUtils.isEmpty(mailId)){
				String text = "Dear Customer, Your Reservation is successfully Done. Your Reservation ID " + reservation.getReservationID();
				String subject = "SuperRent Vehicle reservation Successfull";
				MailSender.send(text, subject, mailId);
			}
			Navigator.loadStackPane(Navigator.ReservationFinalInfo);
		}
		catch(SQLException se)
		{
			errorText.setText("SQL Error");
			errorText.setVisible(true);
			errorText.setText("DB ERROR");
			errorText.setVisible(true);
		}
		// store reservation details
		catch (Exception e) {
			errorText.setText("SQL Error");
			errorText.setVisible(true);
		}
	}

	/**
	 * This Method to navigate to the initial cancel reservation page
	 * 
	 */
	public void cancelReservation(){
		// load cancel reservation frame
		page=5;
		Navigator.loadStackPane(Navigator.CANCELRESERVATION);

	}

	/**
	 * This method enables the price quote button on the Reservation Initial form
	 * @param event
	 */

	@FXML
	public void priceQuoteEnable(ActionEvent event)
	{
		reservation_price_quote.setDisable(false);
	}

	/**
	 * Method to reset all the values on the reservation page
	 * @param event
	 */
	@FXML
	public void resetValues(ActionEvent event)
	{
		page=0;
		Navigator.loadStackPane(Navigator.ReservationInitialFXML);
	}


	/**
	 * This Method fetches the reservation details from the database only when all the required enteries are filled
	 * @pre Reservation Id or phone number and pickupdate are filled with valid values
	 * @post Reservation details are fetched and displayed
	 * @param event
	 */
	@FXML
	public void fetchReservationDetails(ActionEvent event)
	{

		errorText.setVisible(false);
		ReservationLogic rl = new ReservationLogic();
		if(reservationID.getText().isEmpty() && reservationPhoneNumber.getText().isEmpty() && reservation_pickup_date.getValue()==null)
		{
			errorText.setText("Please enter the required value");
			errorText.setVisible(true);
			return;
		}
		else if(reservationID.getText().isEmpty() && reservationPhoneNumber.getText().isEmpty() && reservation_pickup_date.getValue()!=null)
		{
			errorText.setText("Please enter Phone Number");
			errorText.setVisible(true);
			return;
		}
		else if(reservationID.getText().isEmpty() && !reservationPhoneNumber.getText().isEmpty() && reservation_pickup_date.getValue()==null)
		{
			errorText.setText("Please enter the pickupdate");
			errorText.setVisible(true);
			return;
		}

		if(!reservationID.getText().isEmpty())
		{
			if(!Validator.validateStringContainsInteger(reservationID.getText().trim()))
			{
				errorText.setText("Please enter a valid Reservation Number");
				errorText.setVisible(true);
				return;
			}
			System.out.println("search by reservation ID");
			try {
				cancelReservation=rl.fetchReservation(Long.parseLong(reservationID.getText()));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				errorText.setText("DB ERROR");
				errorText.setVisible(true);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				errorText.setText("DB ERROR");
				errorText.setVisible(true);
			}
			/*	if(cancelReservation==null)
			{
				System.out.println("Object is null in Controller");
			}
			else
				System.out.println("Cancel in controller "+cancelReservation.getReservationID());
			 */}
		else if ((!reservationPhoneNumber.getText().isEmpty() && reservation_pickup_date.getValue()!=null))
		{
			if(!Validator.validatePhoneNumber(reservationPhoneNumber.getText()))
			{
				errorText.setText("Please enter a valid Phone Number");
				errorText.setVisible(true);
				return;
			}
			if(!Validator.validateFutureDate(reservation_pickup_date.getValue()))
			{
				errorText.setText("Please enter a valid future Date");
				errorText.setVisible(true);
				return;	
			}
			System.out.println("search by phone number and date");
			try {
				cancelReservation=rl.fetchReservation(reservationPhoneNumber.getText(), reservation_pickup_date.getValue().toString());
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				errorText.setText("DB ERROR");
				errorText.setVisible(true);
			}
			/*	if(cancelReservation==null)
			{
				System.out.println("Object is null in Controller");
			}
			System.out.println("Its here");
			 */}

		if(cancelReservation==null || cancelReservation.getReservationID()==0)
		{
			errorText.setText("No such Reservation record present");
			errorText.setVisible(true);
		}
		else
		{
			System.out.println("Navigating with "+cancelReservation.getReservationID() );
			page=6;
			Navigator.loadStackPane(Navigator.CONFIRMCANCELLATION);
		}
	}


	/**
	 * Event handler method of the Cancel Reservation button which would cancel the
	 * reservation if the reservation is active.
	 * @param event
	 */
	@FXML
	public void cancelReservationConfirm(ActionEvent event){

		if(cancelReservation.getStatus().equalsIgnoreCase("active"))
		{	ReservationLogic rl =new ReservationLogic();
			try {
				rl.cancelReservation(cancelReservation.getReservationID());
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				errorText.setText("DB ERROR");
				errorText.setVisible(true);
			}
			cancelResLabel.setText("Cancellation has been done...");
			cancelResLabel.setVisible(true);
		}
		else if(cancelReservation.getStatus().equalsIgnoreCase("cancelled"))
		{
			cancelResLabel.setText("The reservation is already in Cancelled state.. Cancellation Denied !!");
			cancelResLabel.setVisible(true);
		}
		else if(cancelReservation.getStatus().equalsIgnoreCase("rented"))
		{
			cancelResLabel.setText("The reservation is already in Rented state.. Cancellation Denied !!");
			cancelResLabel.setVisible(true);
		}
		cancelConfirm.setVisible(false);
		
		
	}

	/**
	 * Event handler method of button after the reservation details are displayed
	 * @param event
	 * @return
	 */
	@FXML
	public void reservationDone(ActionEvent event)
	{
		page =-1;
		if(RentController.getSceneNumber()==3)
		{
			Navigator.loadStackPane(Navigator.RentSelectVehicleScreenFXML);
		}
	}

	/**
	 * Initialize method of Reservation Controller which will be invoked on every call to the FXML screen having 
	 * Reservation Controller as the controller class.
	 * 
	 *@return
	 */
	@Override
	public void initialize(URL location, ResourceBundle resources) {
		// TODO Auto-generated method stub

		if(page==-1)
		{
			Validator.addTextLimiter(custName, 30);
			Validator.addTextLimiter(customerPhoneNumber, 10);
			Validator.addTextLimiter(custEmailID, 40);

		}
		else
			if(page==0)
			{ ArrayList<String> timeRange;
			Validator range= new Validator();
			timeRange=range.timeRange();
			reservation_pickup_time.getItems().addAll(timeRange);
			reservation_return_time.getItems().addAll(timeRange);
			}
			else
				if (page==1)
				{
					DecimalFormat df = new DecimalFormat("#0.00");
					vehicleType.setText(reservation.getVehicleType());
					vehicleClass.setText(reservation.getVehicleClass());
					returnDate.setText(reservation.getReturnDate().toString());
					pickupDate.setText(reservation.getPickUpDate().toString());
					ObservableList<String> items =FXCollections.observableArrayList (
							"Rental Cost						:	"+df.format(reservation.getRentalCost())+ "  CAD", 
							"Additional Equipment Cost			:	"+df.format(reservation.getAdditionalEquipmentFees())+ "  CAD",	
							"Insurance Cost						:	"+df.format(reservation.getInsuranceCost())+ "  CAD",
							"Age Fine							:	"+df.format(reservation.getAgeFine())+ "  CAD",	
							"Fees (service fees + age fees)			:	"+df.format(reservation.getFees())+ "  CAD",
							"Taxes							:	"+df.format(reservation.getTax())+ "  CAD",			
							"Total Cost						:	"+Validator.formatDouble(reservation.getEstimatedCost())+ "  CAD");
					priceEst.setItems(items);


				}
				else
					if(page==2)
					{
						ArrayList<String> timeRange;
						Validator range= new Validator();
						timeRange=range.timeRange();
						reservation_pickup_time.getItems().addAll(timeRange);
						reservation_return_time.getItems().addAll(timeRange);
						reservation_vehicle_type.setVisible(true);
						reservation_pickup_time.setValue(reservation.getPickUpTime());
						reservation_pickup_date.setValue(reservation.getPickUpDate());
						reservation_return_time.setValue(reservation.getReturnTime());
						return_date.setValue(reservation.getReturnDate());
						reservation_vehicle_class.setValue(reservation.getVehicleClass());
						reservation_vehicle_capacity.setValue(reservation.getVehicleSpec());
						reservation_driver_age.setValue(reservation.getDriverAge());
						reservation_vehicle_type.setValue(reservation.getVehicleType());
						if(reservation.getAdditionalEquip()==null)
							reservation_vehicle_equipments.setValue("None");
						else
							if(reservation.getAdditionalEquip().size()==2)
								reservation_vehicle_equipments.setValue("Both");
							else
								if(reservation.getAdditionalEquip().size()==1)
									reservation_vehicle_equipments.setValue(reservation.getAdditionalEquip().get(0));

					}
					else if (page==3)
					{
						vehicleType.setText(reservation.getVehicleType());
						vehicleClass.setText(reservation.getVehicleClass());
						returnDate.setText(reservation.getReturnDate().toString()+" / "+reservation.getReturnTime().toString());
						//additionalEquip.setText(reservation.getAdditionalEquip());
						if(reservation.getAdditionalEquip()==null)
						{
							additionalEquip.setText("None");
						}
						else
							if(reservation.getAdditionalEquip().size()==2)
							{
								additionalEquip.setText(reservation.getAdditionalEquip().get(0)+" + "+reservation.getAdditionalEquip().get(1));

							}else if (reservation.getAdditionalEquip().size()==1)
							{
								additionalEquip.setText(reservation.getAdditionalEquip().get(0));
							}
							else
							{
								System.out.println("NONE OF THE SITUATIONS");
							}
						vehicleSpec.setText(reservation.getVehicleSpec());
						pickupDate.setText(reservation.getPickUpDate().toString()+" / "+reservation.getPickUpTime().toString());
						Validator.addTextLimiter(creditCardNo,16);
						Validator.addTextLimiter(expirydate, 4);
					}
					else if(page==4)
					{
						vehicleType.setText(reservation.getVehicleType());
						vehicleClass.setText(reservation.getVehicleClass());
						returnDate.setText(reservation.getReturnDate().toString()+" / "+reservation.getReturnTime().toString());
						//additionalEquip.setText(reservation.getAdditionalEquip());
						if(reservation.getAdditionalEquip()==null)
						{
							additionalEquip.setText("None");
						}
						else
							if(reservation.getAdditionalEquip().size()==2)
							{
								additionalEquip.setText(reservation.getAdditionalEquip().get(0)+" + "+reservation.getAdditionalEquip().get(1));

							}else if (reservation.getAdditionalEquip().size()==1)
							{
								additionalEquip.setText(reservation.getAdditionalEquip().get(0));
							}
							else
							{
								System.out.println("NONE OF THE SITUATIONS");
							}
						vehicleSpec.setText(reservation.getVehicleSpec());
						pickupDate.setText(reservation.getPickUpDate().toString()+" / "+reservation.getPickUpTime().toString());
						rentalCost.setText(""+Validator.formatDouble(reservation.getRentalCost()));
						insuranceCost.setText(""+Validator.formatDouble(reservation.getInsuranceCost()));
						estimatePrice.setText(""+Validator.formatDouble(reservation.getEstimatedCost()));
						creditCardNo.setText(reservation.getCreditCardNumber());
						genReservationID.setText(""+reservation.getReservationID());
						genReservationID.setVisible(true);
						page=-1;
						if(RentController.getSceneNumber()==6)
						{
							RentController.setSceneNumber(3);
							RentController.setReservationEntity(reservation);
							Navigator.loadStackPane(Navigator.RentSelectVehicleScreenFXML);
						}
					}
					else if(page==5)
					{
						Validator.addTextLimiter(reservationID, 10);
						Validator.addTextLimiter(reservationPhoneNumber, 10);
					}
					else if(page==6)
					{
						vehicleType.setText(cancelReservation.getVehicleType());
						vehicleClass.setText(cancelReservation.getVehicleClass());
						returnDate.setText(cancelReservation.getReturnDate().toString()+" / "+cancelReservation.getReturnTime().toString());
						if(cancelReservation.getAdditionalEquip()==null)
						{
							additionalEquip.setText("None");
						}
						else
							if(cancelReservation.getAdditionalEquip().size()==2)
							{
								additionalEquip.setText(cancelReservation.getAdditionalEquip().get(0)+" + "+cancelReservation.getAdditionalEquip().get(1));

							}else if (cancelReservation.getAdditionalEquip().size()==1)
							{
								additionalEquip.setText(cancelReservation.getAdditionalEquip().get(0));
							}
							else
							{
								System.out.println("NONE OF THE SITUATIONS");
							}
						vehicleSpec.setText(cancelReservation.getVehicleSpec());
						pickupDate.setText(cancelReservation.getPickUpDate().toString()+" / "+cancelReservation.getPickUpTime().toString());
						rentalCost.setText(""+Validator.formatDouble(cancelReservation.getRentalCost()));
						insuranceCost.setText(""+Validator.formatDouble(cancelReservation.getInsuranceCost()));
						estimatePrice.setText(""+Validator.formatDouble(cancelReservation.getEstimatedCost()));
						try {
							creditCardNo.setText(Encrypt.decrypt(cancelReservation.getCreditCardNumber()));
						} catch (Exception e) {
							e.printStackTrace();
						}
						genReservationID.setText(""+cancelReservation.getReservationID());
						genReservationID.setVisible(true);
						page=-1;
					}
	}

	public static int getPage() {
		return page;
	}

	public static void setPage(int page) {
		ReservationController.page = page;
	}

}
